
class URL:
  
  def __init__(self, path):
    # Setup defaults
    self.query_data = {}
    self.anchor = ''
    self.protocol = 'http://'
    self.path = '/'
    self.domain = ''
    self.subdomain = ''
    
    # Parse the given path
    self.setPath(path)
    
  def __str__(self):
    return self.toString()
    
  def toAbsoluteString(self):
    bits = [self.protocol, self.subdomain, '.', self.domain]
    bits.append(self.toRelativeString())
    
  def toRelativeString(self):
    bits = []
    bits.append(self.path)
    if self.query_data:
      bits.append('?')
      for key in self.query_data:
        bits.append('%s=%s' % (key, self.query_data[key]))
    if self.anchor:
      bits.append('#%s' % self.anchor)
    return ''.join(bits)
  
  def toString(self):
    if self.domain:
      return self.toAbsoluteString()
    else:
      return self.toRelativeString()
  
  def clearQueryData(self):
    self.setQueryData({})
  
  def addQueryData(self, key, value):
    self.query_data[key] = value
    
  def removeQueryData(self, keys):
    try:
      for key in keys:
        try:
          self.query_data.pop(key)
        except KeyError:
          pass
    except TypeError:
      try:
        self.query_data.pop(key)
      except KeyError:
        pass
    
  def appendQueryData(self, query_dict):
    self.query_data.extend(query_data)
  
  def setQueryData(self, query_data):
    self.query_data = query_data
    
  def setAnchor(self, anchor):
    self.anchor = anchor
  
  def clearAnchor(self):
    self.setAnchor('')
  
  def getAnchor(self):
    return self.anchor
  
  def setProtocol(self, protocol):
    if protocol.find('://') < 0:
      raise ValueError('Protocol must contain ://')
    self.protocol = protocol
  
  def getProtocol(self):
    return self.protocol
  
  def clearProtocol(self):
    self.setProtocol('http://')
    
  def setDomain(self, domain):
    self.domain = domain
  
  def getDomain(self):
    return self.domain
  
  def clearDomain(self):
    self.setDomain('')
  
  def setSubdomain(self, subdomain):
    self.subdomain = subdomain
  
  def getSubdomain(self):
    return self.subdomain
  
  def clearSubdomain(self):
    self.setSubdomain('')
    
  def setPath(self, path):
    if not path or path[0] != '/':
      path = '/%s' % path
    self.path = path
  
  def getPath(self):
    return self.path
  
  def clearPath(self):
    self.setPath('/')